package com.tongda.core.message.tts;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import android.os.Handler;

import com.tongda.core.common.Constants;

/**
 * 
 * @author andy
 * 
 */
public class GoogleHelper {
	public static final int SHIBIE_END = 0;
	public static final int SHIBIE_ERRO = 1;
	public static final String nameWav = "/GoogleTalk.wav";
	public static final String nameFlac = "/GoogleTalk.flac";
	public static final String sdcardPath = Constants.FILE_BASE_PATH;

	public static String post(String filePath) throws Exception {
		// zh-CN en-US audio/L16 audio/x-flac
		URL url = new URL(
				"http://www.google.com/speech-api/v1/recognize?xjerr=1&client=chromium&lang=zh-CN&maxresults=1");
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setDoOutput(true);
		conn.setDoInput(true);
		conn.setRequestMethod("POST");

		conn.setRequestProperty("Content-Type", "audio/x-flac; rate=8000");
		DataOutputStream writer = new DataOutputStream(conn.getOutputStream());
		FileInputStream input = new FileInputStream(new File(filePath));
		byte[] buffer = new byte[256];
		int read = input.read(buffer);
		while (read != -1) {
			writer.write(buffer, 0, read);
			read = input.read(buffer);
		}
		writer.flush();
		writer.close();
		input.close();
		InputStreamReader reder = new InputStreamReader(conn.getInputStream(),
				"utf-8");
		BufferedReader breader = new BufferedReader(reder);
		String content = null;
		String result = "";
		while ((content = breader.readLine()) != null) {
			result += content + "\n";
		}
		return result;

	}

	/**
	 * 录制wav格式文件
	 */
	public static void recordChat(ExtraAudioRecorder extAudioRecorder,
			Handler handler) {
		if (extAudioRecorder != null) {
			String savePath = GoogleHelper.sdcardPath;
			String fileName = GoogleHelper.nameWav;
			File dir = new File(savePath);
			File file = new File(savePath + fileName);
			if (file.isFile()) {
				file.delete();
			}
			if (dir.list() == null) {
				dir.mkdirs();
			}
			extAudioRecorder.setOutputFile(savePath + fileName);
			extAudioRecorder.prepare();
			//
			extAudioRecorder.start(handler);
			System.err.println("stt录制开始");
		}
	}

	public static void stopRecord(ExtraAudioRecorder extAudioRecorder) {
		if (extAudioRecorder != null) {
			System.err.println("stt录制结束");
			extAudioRecorder.stop();
			extAudioRecorder.release();
		}
	}
}
